package com.example.dw.config;

import com.example.dw.utils.AdminJwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;

/**
 * 管理端JWT认证过滤器
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Component
public class AdminJwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private AdminJwtUtil adminJwtUtil;

    // 管理端不需要认证的接口
    private static final List<String> EXCLUDED_PATHS = Arrays.asList(
            "/admin/login"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        String requestPath = request.getServletPath();
        
        // 只处理管理端接口
        if (!requestPath.startsWith("/admin")) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 跳过不需要认证的路径
        if (shouldSkipFilter(requestPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        String authorizationHeader = request.getHeader("Authorization");
        
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            
            try {
                if (adminJwtUtil.validateAdminToken(token)) {
                    String adminUsername = adminJwtUtil.getAdminUsernameFromToken(token);
                    String role = adminJwtUtil.getRoleFromToken(token);
                    
                    if (adminUsername != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                        // 创建管理员权限
                        List<SimpleGrantedAuthority> authorities = Collections.singletonList(
                            new SimpleGrantedAuthority("ROLE_" + role)
                        );
                        
                        UsernamePasswordAuthenticationToken authToken = 
                                new UsernamePasswordAuthenticationToken(
                                        adminUsername, null, authorities);
                        authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        SecurityContextHolder.getContext().setAuthentication(authToken);
                        
                        // 将管理员ID和角色存储到request属性中，供Controller使用
                        Integer adminId = adminJwtUtil.getAdminIdFromToken(token);
                        request.setAttribute("adminId", adminId);
                        request.setAttribute("adminUsername", adminUsername);
                        request.setAttribute("role", role);
                    }
                }
            } catch (Exception e) {
                log.error("管理端JWT认证失败: {}", e.getMessage());
            }
        }
        
        filterChain.doFilter(request, response);
    }

    private boolean shouldSkipFilter(String requestPath) {
        return EXCLUDED_PATHS.stream().anyMatch(requestPath::startsWith);
    }
} 